/**
 * 上海中赢金融信息服务有限公司
 * Copyright (c) 2017-2027 Chinazyjr,Inc.All Rights Reserved.
 */
package com.sys.midware.MQ.rocketMQ.factory;

import com.sys.midware.MQ.rocketMQ.config.ConfigRocketUtil;
import com.sys.midware.MQ.rocketMQ.logic.IPullConsumer;
import com.sys.midware.MQ.rocketMQ.logic.impl.PullConsumerImpl;
import com.sys.midware.assist.utils.string.StringUtil;
import com.sys.midware.logger.Logger;
import com.sys.midware.logger.LoggerFactory;

/**
 * 
 * <b>ClassName：</b> ConsumerFactory <br/>
 * <b>Description：</b> 获取默认的消息消费实例 <br/>
 * <b>@author：</b> mobing <br/>
 * <b>@date：</b> 2015年10月19日 下午2:55:46 <br/>
 * <b>@version: </b>  <br/>
 */
public class PullConsumerFactory {
    private static final Logger logger = LoggerFactory.getLogger(PullConsumerFactory.class);
	/**
	 * IConsumer 接口定义
	 */
	private static IPullConsumer consumer = null;

	public static IPullConsumer getConsumerInstace(){
	    return getConsumerInstace(null);
	}

	/**
	 * 获取消费者实例
	 * @param consumerGroup  消费实例 
	 * @return  IPullConsumer
	 */
	public static IPullConsumer getConsumerInstace(String consumerGroup) {

		if (null != consumer) {
			return consumer;
		}
		if (StringUtil.isEmpty(consumerGroup)) {
			consumerGroup = ConfigRocketUtil.getMQGroupConsumer();
		}
		synchronized (PullConsumerFactory.class) {
			if (null == consumer) {
			    // set name server
		        String  nameServer = ConfigRocketUtil.getRocketNameServer();
				consumer = new PullConsumerImpl(nameServer,consumerGroup);
                consumer.start();
				Runtime.getRuntime().addShutdownHook(new CleanHook());
			}
		}
		
		return consumer;
	}
	
	
    static void clean() {
        try {
            logger.info("shutdown pullConsumer...");
            consumer.shutdown();
            logger.info("shutdown pullConsumer finish!");
        } catch (Exception e) {
            logger.error("shutdown pullConsumer error!", e);
        }
    }

    static class CleanHook extends Thread {
        public void run() {
            clean();
        }
    }
	
}
